<?php
if (!defined('__COLA_DIR__')) exit;

/**
 * 编辑风格组件
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Themes_Edit extends Widget_Abstract_Options implements Widget_Interface_Do
{
    /**
     * 更换外观
     *
     * @access public
     * @param string $theme 外观名称
     * @return void
     * @throws Widget_Exception
     */
    public function changeTheme($theme)
    {
        $theme = trim($theme, './');
        if (is_dir($this->options->themeFile($theme))) {
            /** 删除原外观设置信息 */
            $this->delete('theme:' . $this->options->theme);

            $this->update('theme', $theme);

			$this->result->set(0, _t("外观已经改变"));
        } else {
			$this->result->set(-1, _t("您选择的风格不存在"));
        }
    }

    /**
     * 编辑外观文件
     *
     * @access public
     * @param string $theme 外观名称
     * @param string $file 文件名
     * @return void
     * @throws Widget_Exception
     */
    public function editThemeFile($theme, $file)
    {
        $path = $this->options->themeFile($theme, $file);

        if (file_exists($path) && is_writeable($path) && !Common::isAppEngine()) {
            $handle = fopen($path, 'wb');
            if ($handle && fwrite($handle, $this->request->content)) {
                fclose($handle);
                $this->result->set(0, _t("文件 %s 的更改已经保存", $file));
            } else {
                $this->result->set(1, _t("文件 %s 无法被写入", $file));
            }
        } else {
            throw new Widget_Exception(_t('您编辑的文件不存在'));
        }
    }
    
    /**
     * 配置外观
     *
     * @access public
     * @param string $theme 外观名
     * @return void
     */
    public function config($theme)
    {
        // 已经载入了外观函数
        $form = $this->widget('Widget_Themes_Config')->form();
		
		/** 验证表单 */
        if ($message = $form->validate()) {
            $this->result->set(key($message), current($message));
        }

        $settings = $form->getAllRequest();
        if ($this->options->__get('theme:' . $theme)) {
            $this->update('theme:' . $theme, serialize($settings));
        } else {
            $this->insert(array('name' => 'theme:' . $theme, 'value' => serialize($settings)));
        }

        /** 提示信息 */
        $this->result->set(0, _t("外观设置已经保存"));
    }

    /**
     * 绑定动作
     *
     * @access public
     * @return void
     */
    public function action()
    {
		$this->user->pass('admin');
        $this->security->protect();
        $this->on($this->request->is('change'))->changeTheme($this->request->filter('strip_tags')->change);
        $this->on($this->request->is('edit&theme'))
            ->editThemeFile($this->request->filter('strip_tags')->theme, $this->request->edit);
        $this->on($this->request->is('config'))->config($this->options->theme);
		$this->result->set(404, _t('请求的资源不存在'));
    }
}
